<?php
namespace app\client\controller;
use app\client\wxpay\Notify as WxNotify;
use app\client\wxpay\Config;
use think\swoole\facade\Task;

class Notify {
    
    private $notify = null;
    private $config = null;
    
    public function __construct() {
        $this->notify = new WxNotify();
        $this->config = new Config();
    }
    
    /* $msg = 'ok';
    PayHandle::lbsChatRedenvelope(['openid' => 'abc123', 'transaction_id' => '123456', 'total_fee' => 1000, 'out_trade_no' => '201903255657979702021'], $msg, 0);
    var_dump($msg);
    return 3233; */
    
    public function chatRedenvelopeNotify() { //LBS红包的
        
        try {
            $this->notify->action = 'chatRedenvelopeNotify';
            $this->notify->Handle($this->config, false);
            $this->_log(1);
        } catch (\Exception $e) {
            
        }
        
        return '';
    }
    
    
    public function goodsRedenvelopeNotify() { //产品红包支付
        try {
            $this->notify->action = 'goodsRedenvelopeNotify';
            $this->notify->Handle($this->config, false);
            $this->_log(4);
        } catch (\Exception $e) {
            
        }
        
        return '';
    }
    
    public function merchatApplyNotify() { //申请成为商家
        try {
            $this->notify->action = 'merchatapplyNotify';
            $this->notify->Handle($this->config, false);
            $this->_log(5);
        } catch (\Exception $e) {
            
        }
        
        return '';
    }
    
    public function agentApplyNotify() { //申请成为代理
        try {
            $this->notify->action = 'agentApplyNotify';
            $this->notify->Handle($this->config, false);
            $this->_log(5);
        } catch (\Exception $e) {
            
        }
        
        return '';
    }
    
    private function _log($type) {
        if(!$this->notify->payResult){
            $data = $this->notify->callbackData;
            $orderNo = $this->notify->orderNo;
            $tradeNo = $this->notify->tradeNo;
            $msg = $this->notify->msg;
            
            $logModel = model('PayErrorLog');
            
            Task::async(function() use($data, $orderNo, $tradeNo, $msg, $logModel, $type){
                try {
                    $logModel->add(['order_no' => $orderNo, 'trade_no' => $tradeNo, 'msg' => $msg, 'data' => $data, 'type' => $type, 'add_time' => date('Y-m-d H:i:s')]);
                    unset($logModel);
                } catch (\Exception $e) {
                    
                }
            });
        }
    }
}



